
/**
 * 滑动类
 */
class MySlide {
    constructor(initIndex) {
        this.prev = initIndex; 
        this.myslide_class = '.myslide-item';
        this.items = document.querySelectorAll(this.myslide_class);
        this.adjust(initIndex);
    }

    /**
     * 滑动到新页面
     * @param {*} index 目标页面
     */
    slideTo(index) {
        if(index === this.prev) return;
        if(index > this.prev) {
            //向左滑动
            this.slideToLeft(index);
        } else {
            //向右滑动
            this.slideToRight(index);
        }
    }

    //向左滑动
    slideToLeft(index) {
        let prevItem = this.items[this.prev];
        let curItem = this.items[index];
        prevItem.style.transform = 'translate(-100%)';
        curItem.style.transform = 'translate(0)';
        this.prev = index;
        this.adjust(index);
    }

    //向右滑动
    slideToRight(index) {
        let prevItem = this.items[this.prev];
        let curItem = this.items[index];
        prevItem.style.transform = 'translate(100%)';
        curItem.style.transform = 'translate(0)';
        this.prev = index;
        this.adjust(index);
    }

    /**
     * 重新调整slide的页面，把小于当前页的页面挪到左边
     */
    adjust(index) {
        setTimeout(()=>{
            for(let i=0;i<this.items.length;i++) {
                if(i<index) {
                    this.items[i].style.transform = 'translate(-100%)';
                }
            }
        });
    }

    /**
     * 向左滑动 （过渡）
     * @param {*} index 
     * @param {*} distance 
     */
    moveLeft(index,distance) {
        let prevItem = this.items[this.prev];
        let curItem = this.items[index];
        let prevItemPersent = (distance/414*100).toFixed(3);
        let curItemPersent = 100-prevItemPersent;
        prevItem.style.transform = 'translate(-'+prevItemPersent+'%)';
        curItem.style.transform = 'translate('+curItemPersent+'%)';
    }
    //向左滑动失败，恢复原样
    moveLeftReset(index) {
        let prevItem = this.items[this.prev];
        let curItem = this.items[index];
        prevItem.style.transform = 'translate(0)';
        curItem.style.transform = 'translate(100%)';
    }

    /**
     * 向右滑动（过渡）
     * @param {*} index 
     * @param {*} distance 
     */
    moveRight(index,distance) {
        let prevItem = this.items[this.prev];
        let curItem = this.items[index];
        let curItemPersent = (distance/414*100).toFixed(3);
        let prevItemPersent = 100-curItemPersent;
        prevItem.style.transform = 'translate('+curItemPersent+'%)';
        curItem.style.transform = 'translate(-'+prevItemPersent+'%)';
    }
    /**
     * 向右滑动失败，恢复原样
     * @param {*} index 
     */
    moveRightReset(index) {
        let prevItem = this.items[this.prev];
        let curItem = this.items[index];
        prevItem.style.transform = 'translate(0)';
        curItem.style.transform = 'translate(-100%)';
    }
}

module.exports  = MySlide;